function moveFile() {

}

function renameFile() {

    var selection = Ext.getCmp('fileTreePanel').getSelection()
    if (selection.length != 0) {
        var temp = selection[0].data.fileName
        Ext.MessageBox.prompt('修改名称', '请输入新的名称:', function(btn, text){
            if (btn=="ok") {
                console.log(selection[0])
                if(text==null||text=="") {
                    alert("请输入名称")
                    return
                }
                Ext.Ajax.request({
                    url: "../file/rename",
                    params: {
                        fileName: text,
                        id:selection[0].data.id,
                        parentFileId: selection[0].data.parentFileId,
                        isDir: selection[0].data.isDir,
                    },
                    success: function(response, opts) {
                        var res = Ext.JSON.decode(response.responseText)
                        if(res.success) {
                            Ext.toast('重命名成功！');
                            selection[0].set("fileName",text)
                        } else {
                            alert(res.message);
                            renameFile()
                        }
                    }
                });
            }
        }, this,false,temp);

    }

}

function saveFile() {
    if (Ext.getCmp('fileName').getValue() == "") {
        alert("请输入文件名")
        return
    }
    var parentFileId
    var selection = Ext.getCmp('fileTreePanel').getSelection()
    if (selection.length != 0) {
        console.log(selection[0].data.parentFileId)
        if (selection[0].data.isDir) {
            parentFileId = selection[0].data.id
        } else {
            parentFileId = selection[0].data.parentFileId
        }
        console.log(parentFileId)

    }

    var chartDatasource = nowDataSource
    if (nowDsActiveTab=="文件数据") {
        chartDatasource = "-1"
    }

    if (nowDsActiveTab=="远程数据") {
        chartDatasource = "-2"
    }

    Ext.Ajax.request({
        url: "../file/save",
        params: {
            eventClickSource:window.eventClickSource,
            eventDblclickSource:window.eventDblclickSource,
            eventMousedownSource:window.eventMousedownSource,
            eventMousemoveSource:window.eventMousemoveSource,
            eventMouseupSource:window.eventMouseupSource,
            eventMouseoverSource:window.eventMouseoverSource,
            eventMouseoutSource:window.eventMouseoutSource,
            displayTable:displayTable,
            dynamicSeries:dynamicSeries,
            refreshTime:refreshTime,
            rowMode:rowMode,
            fileName: Ext.getCmp('fileName').getValue(),
            token: Ext.create('Ext.data.identifier.Uuid').generate().replace(/-/g,""),
            parentFileId: parentFileId,
            isDir: false,
            oldChartId:chartId,
            chartDatasource: chartDatasource,
            remoteUrl:nowRemoteUrl,
            nowRemoteAdapterId:nowRemoteAdapterId,
            chartSql: chartSql,
            chartSource: $('#sourceContent2').html(),
            themeId:nowChartTheme,
            tableThemeId:nowTableTheme
        },
        success: function(response, opts) {
            var res = Ext.JSON.decode(response.responseText)
            console.log(res)
            chartId = res.chartFile.id
            uuid = res.chartFile.token
            fileName = res.chartFile.fileName
            parentFileId = res.chartFile.parentFileId
            dateCreated = new Date(res.chartFile.dateCreated)
            dateCreated = Ext.Date.format(dateCreated, 'Y-m-d H:i')
            lastUpdated = new Date(res.chartFile.lastUpdated)
            lastUpdated = Ext.Date.format(lastUpdated, 'Y-m-d H:i')
                //chartSql = res.chartFile.chartSql
                //chartSource = Ext.JSON.decode(res.chartFile.chartSource)
            Ext.getCmp('chartProperty').enable()
            Ext.getCmp('profilePanel').setTitle(res.chartFile.fileName)
            fileWindow.close()
            Ext.toast('图表保存成功！');
        }
    });
}

function openFile() {
    var selection = Ext.getCmp('fileTreePanel').getSelection()
    console.log(selection.length)
    if (selection.length!=0) {
        Ext.MessageBox.show({
            msg: '正在打开图表文件, 请等待...',
            progressText: 'Loading...',
            width: 300,
            wait: {
                interval: 200
            }
        });
        window.location="edit?id="+selection[0].data.id
    } else {

    }

}


function createDir() {

    Ext.MessageBox.prompt('新建目录', '请输入目录名称:', function(btn, text){
        if (btn=="ok") {
            if(text==null||text=="") {
                alert("请输入目录名称")
                return
            }
            var parentFileId
            if (Ext.getCmp('fileTreePanel').getSelection().length!=0) {
                parentFileId = Ext.getCmp('fileTreePanel').getSelection()[0].data.id
                
            } 
            Ext.Ajax.request({
                url: "../file/save",
                params: {
                    fileName:text,
                    parentFileId:parentFileId,
                    isDir:true
                },
                success:function(response, opts) {
                    var res = Ext.JSON.decode(response.responseText)
                    if (res.success) {


                    } else {
                        alert('目录已存在请重新输入目录名称')
                        createDir()
                    }
                    Ext.getCmp('fileTreePanel').getStore().load()                                                       
                }
            }); 
        }
    }, this);

    
    
}

function deleteDirOrFile(btn, text) {
    if (btn=="yes") {
        var selection = Ext.getCmp('fileTreePanel').getSelection()
        if((selection[0].data.id+"")==(chartId+"")) {
            alert("此文件当前被打开，无法删除")
            return
        }

        if (selection.length>0) {
            Ext.Ajax.request({
                url: "../file/delete",
                params: {
                    id:selection[0].data.id,
                },
                success:function(response, opts) {
                    Ext.getCmp('fileTreePanel').getStore().load()                                  
                }
            }); 
        }
    }
}


var fileWindow = Ext.create('Ext.window.Window', {
    title: '文件框',
    //iconCls:'x-fa fa-database',
    height: 600,
    width: 900,
    //layout: 'fit',
    modal:true,
    closeAction:'hide',
    layout: 'border',
    defaults: {
        collapsible: false,
        split: true,
        bodyPadding: 0
    }, 
    items:[
        {
            title: '',
            region: 'south',
            //height: 65,
            width:'100%',
            scrollable: true,
            items:[
                {
                    xtype:'textfield',
                    id:'fileName',
                    labelWidth:600,
                    labelAlign:'right',
                    width:850,
                    fieldLabel: '图表名称'
                }
            ]
        },
        /*{
            title: '',
            region: 'west',
            width: 300,
            scrollable: true,
            items:[]
        },*/
        {
            title: '',
            region: 'center',
            //width: 500,
            scrollable: true,
            tbar: [
                { 
                    xtype: 'button', 
                    text: '增加目录',
                    iconCls:'x-fa fa-plus',
                    id:'addDir',
                    handler:function() {
                        createDir()
                    } 
                },
                { 
                    xtype: 'button', 
                    text: '删除目录/文件',
                    id:'delDirOrFile',
                    disabled:true,
                    iconCls:'x-fa fa-pencil',
                    handler:function() {

                        Ext.MessageBox.confirm('删除确认', '是否删除?', deleteDirOrFile, this);

                    }
                },
                { 
                    xtype: 'button', 
                    text: '重命名目录/文件',
                    id:'renameDirOrFile',
                    disabled:true,
                    //iconCls:'x-fa fa-pencil',
                    handler:function() {
                       renameFile()
                    } 
                },
                { 
                    xtype: 'button', 
                    text: '复制',
                    iconCls:'x-fa fa-copy',
                    handler:function() {
                        var selection = Ext.getCmp('fileTreePanel').getSelection()
                        if (selection.length!=0&&!Ext.getCmp('fileTreePanel').getSelection()[0].data.isDir) {
                            window.copyChartFileId = Ext.getCmp('fileTreePanel').getSelection()[0].data.id
                            window.copyChartFileName = Ext.getCmp('fileTreePanel').getSelection()[0].data.fileName
                        } else {
                            alert("请选择图表文件")
                        }
                    } 
                },
                { 
                    xtype: 'button', 
                    text: '粘贴',
                    iconCls:'x-fa fa-paste',
                    handler:function() {
                       if (window.copyChartFileId!=null) {

                            Ext.MessageBox.prompt('修改名称', '请输入新的名称:', function(btn, text){
                                if (btn=="ok") {
                                    var parentFileId
                                    if(text==null||text=="") {
                                        alert("请输入名称")
                                        return
                                    }
                                    
                                    var selection = Ext.getCmp('fileTreePanel').getSelection()
                                    if (selection.length>0) {
                                        if (selection[0].data.isDir) {
                                            parentFileId = selection[0].data.id
                                        } else {
                                            parentFileId = selection[0].data.parentFileId
                                        }
                                    } 
                                    Ext.Ajax.request({
                                        url: "../file/paste",
                                        params: {
                                            id:window.copyChartFileId,
                                            parentFileId:parentFileId,
                                            fileName:text,
                                        },
                                        success: function(response, opts) {
                                            var res = Ext.JSON.decode(response.responseText)
                                            if(res.success) {
                                                Ext.getCmp('fileTreePanel').getStore().load()
                                            } else {
                                                alert(res.message) 
                                            }
                                        }
                                    });

                                }
                            }, this,false,window.copyChartFileName);

                            
                       }
                    } 
                }
            ],
            items:[
                {
                    xtype:'treepanel',
                    viewConfig:{
                        plugins :{
                            ptype:'treeviewdragdrop',
                            appendOnly:true,
                            dragText: '移动中'  //dragText: 'Drag and drop to reorganize'       
                        },
                        listeners:{//监听器
                            drop:function(node,data,overModel,dropPosition,options){
                                
                                //alert("把:"+data.records[0].get('text')+" 移动到："+overModel.get("text"));              
                                Ext.Ajax.request({
                                    url: "../file/move",
                                    params: {
                                        id:data.records[0].data.id,
                                        parentFileId:overModel.data.id
                                    },
                                    success: function(response, opts) {
                                        var res = Ext.JSON.decode(response.responseText)
                                        if(res.success) {
                                            Ext.toast('移动成功！');
                                            Ext.getCmp('fileTreePanel').getStore().load()
                                        } else {
                                            alert(res.message);
                                            renameFile()
                                        }
                                    }
                                });
                            },
                            beforedrop:function(node,data,overModel,dropPosition,dropFunction,options){
                                //   if(overModel.get("leaf")){          
                                //      overModel.set('leaf',false);
                                //   }
                            }
                        }
                    },
                    id:'fileTreePanel',
                    allowDeselect:true,
                    scrollable:true,
                    reserveScrollbar: true,
                    useArrows: true,
                    rootVisible: false,
                    multiSelect: false,
                    singleExpand: false,
                    listeners:{
                        select:function(obj, record, index, eOpts){
                            
                            Ext.getCmp('delDirOrFile').enable()
                            Ext.getCmp('renameDirOrFile').enable()
                            if (record.data.isDir) {
                                Ext.getCmp('addDir').enable()
                            } else {
                                Ext.getCmp('addDir').disable()
                                Ext.getCmp('fileName').setValue(record.data.fileName)
                            }


                            if (fileWindow.getTitle()=="打开") {
                                if (record.data.isDir) {
                                    Ext.getCmp('fileYesBtn').disable()
                                } else {
                                    Ext.getCmp('fileYesBtn').enable()
                                }
                            }

                        }, 
                        deselect:function( obj, record, index, eOpts ) {
                            Ext.getCmp('delDirOrFile').disable()
                            Ext.getCmp('renameDirOrFile').disable()
                            Ext.getCmp('addDir').enable()
                            if (fileWindow.getTitle()=="打开") {
                                Ext.getCmp('fileYesBtn').disable()
                            }
                        }
                    },
                    store: {
                        listeners:{
                            load :function( obj, records, successful, operation, node, eOpts ) {
                               Ext.getCmp('fileTreePanel').expandAll()
                               if (fileWindow.getTitle()=="打开") {
                                    var selection = Ext.getCmp('fileTreePanel').getSelection()
                                    if (selection.length!=0) {
                                        Ext.getCmp('fileYesBtn').enable() 
                                    } else {
                                        Ext.getCmp('fileYesBtn').disable()
                                    }
                               } else {
                                    Ext.getCmp('fileYesBtn').enable()
                               }
                               
                            },
                            select:function() {

                            }
                        },
                        type: 'tree',
                        proxy: {
                            type: 'ajax',
                            url: '../file/store'
                        }
                    },
                    columns: [
                        {
                            xtype: 'treecolumn', 
                            text: '目录/文件',
                            dataIndex: 'fileName',
                            flex: 1
                        }, 
                        {
                            text: '创建日期',
                            dataIndex: 'dateCreated',
                            flex: 1,
                            sortable: true,
                            align: 'center',
                            renderer: function(value){
                                return Ext.Date.format(new Date(value), 'Y-m-d H:i')
                            }
                        }, 
                        {
                            text: '修改日期',
                            dataIndex: 'lastUpdated',
                            flex: 1,
                            sortable: true,
                            align: 'center',
                            renderer: function(value){
                                return Ext.Date.format(new Date(value), 'Y-m-d H:i')
                            }
                        }, 
                        {
                            text: '访问链接',
                            dataIndex: 'token',
                            flex: 1,
                            sortable: true,
                            align: 'center',
                            renderer: function(value){
                                if (value==null||value=="") {
                                    return value
                                } else {
                                    return "<a href='../chart/preview?token="+value+"' target='_blank'>"+value+"</a>"
                                }
                                
                            }
                        }
                    ]
                }

            ]
        }
    ],
    buttons: [
        {
            xtype: 'button',
            text: '取消',
            handler: function() {
                fileWindow.close()
            }
        },
        {
            xtype: 'button',
            id:'fileYesBtn',
            text: '确定',
            handler: function() {
                if (fileWindow.getTitle()=="打开") {
                    openFile()
                } else {
                    saveFile()
                }
            }
        }
    ]
})